<template>
  <XrCreateSingle :loading="loading"
                  :title="title"
                  @close="close"
                  @save="saveClick">
    <CreateSections title="基本信息">
      <el-form ref="crmFormRef"
               :model="fieldForm"
               :rules="fieldRules"
               :validate-on-rule-change="false"
               class="wk-form"
               label-position="top">
        <WkFormItems v-for="(children, index) in fieldList" :key="index"
                     :field-from="fieldForm" :field-list="children"
                     @change="formChange">
        </WkFormItems>
      </el-form>
    </CreateSections>
  </XrCreateSingle>
</template>

<script setup>
import XrCreateSingle from '/src/szcomponent/XrCreateSingle'
import CreateSections from '/src/components/CreateSections'
import WkFormItems from '/src/components/NewCom/WkForm/WkFormItems'
import {useSzCustomFields} from "@/views/crm/hooks/create/useSzCustomFields.js";
import {ElMessage} from "element-plus"
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {filedGetFieldAPI} from "@/api/crm/common.js";
import {crmProductSaveAPI} from "@/api/crm/product.js";
import {crmContactsSaveAPI} from "@/api/crm/contacts.js";
import CrmRelativeCell from "components/CreateCom/CrmRelativeCell.vue";
import XhBusinessStatus from "components/CreateCom/XhBusinessStatus.vue";
import XhProduct from "components/CreateCom/XhProduct.vue";
import {crmLeadsSaveAPI} from "@/api/crm/leads.js";

defineOptions({
  // 新建编辑
  name: 'LeadsCreate',
})

const props = defineProps({
  action: {
    type: Object,
    default: () => {
      return {
        type: 'save',
        id: '',
        data: {}
      }
    }
  }
})

const emits = defineEmits(['save-success', 'close'])

const loading = ref(false)
const ignoreFields = ref(['status'])
const baseFields = ref([])
const fieldList = ref([])
const fieldForm = ref({})
const fieldRules = ref({})
// 图片信息
const imageData = ref({
  mainFile: [],
  detailFile: []
})

const createOption = reactive({
  loading, ignoreFields, baseFields, fieldList, fieldForm, fieldRules, imageData
})

const hookCustomFields = useSzCustomFields(toRef(props, "action"), toRef(fieldRules))

const crmFormRef = ref()

const title = computed(() => {
  return props.action.type === 'update' ? '编辑线索' : '新建线索'
})


function created() {
  getField()
}

created()


/**
 * 获取数据
 */
function getField() {
  createOption.loading = true
  const params = {
    label: crmTypeModel.leads
  }

  if (props.action.type == 'update') {
    params.id = props.action.id
  }

  filedGetFieldAPI(params).then(res => {
    const list = res.data.data || []

    const assistIds = hookCustomFields.getFormAssistIds(list)

    const baseFields = []
    const fieldList = []
    const fieldRules = {}
    const fieldForm = {}
    list.forEach(children => {
      const fields = []
      children.forEach(item => {
        const temp = hookCustomFields.getFormItemDefaultProperty(item)
        temp.show = !assistIds.includes(item.formAssistId)

        if (createOption.ignoreFields.includes(temp.field)) {
          // 防止影响普通单选的验证方式
          delete temp.optionsData
          delete item.optionsData
        }

        const canEdit = hookCustomFields.getItemIsCanEdit(item, props.action.type)
        // 是否能编辑权限
        if (temp.show && canEdit) {
          fieldRules[temp.field] = hookCustomFields.getRules(item)
        }

        // 是否可编辑
        temp.disabled = !canEdit

        // 特殊字段允许多选
        hookCustomFields.getItemRadio(item, temp)

        // 获取默认值
        if (temp.show) {
          if (createOption.ignoreFields.includes(temp.field)) {
            fieldForm[temp.field] = props.action.type === 'update' ? temp.value : temp.defaultValue
          } else {
            fieldForm[temp.field] = hookCustomFields.getItemValue(item, props.action.data, props.action.type)
          }
        }
        fields.push(temp)
        baseFields.push(item)
      })
      fieldList.push(fields)
    })

    createOption.baseFields = baseFields
    createOption.fieldList = fieldList
    createOption.fieldForm = fieldForm
    createOption.fieldRules = fieldRules

    createOption.loading = false
  }).catch(() => {
    createOption.loading = false
  })
}

/**
 * 保存
 */
function saveClick() {
  createOption.loading = true
  // const crmForm = .$refs.crmForm
  crmFormRef.value.validate(valid => {
    if (valid) {
      const params = hookCustomFields.getSubmiteParams([].concat.apply([], createOption.fieldList), createOption.fieldForm)
      // 图片信息
      params.entity.mainFileIds = createOption.imageData.mainFile ? createOption.imageData.mainFile.map(item => item.fileId).join(',') : ''
      params.entity.detailFileIds = createOption.imageData.detailFile ? createOption.imageData.detailFile.map(item => item.fileId).join(',') : ''
      submitParams(params)
    } else {
      createOption.loading = false
      // 提示第一个error
      hookCustomFields.getFormErrorMessage(crmFormRef.value)
      // return false
    }
  })
}

/**
 * 提交上传
 */
function submitParams(params) {
  if (props.action.type == 'update') {
    params.entity.leadsId = props.action.id
    params.entity.batchId = props.action.batchId
  }
  // 相关添加时候的多余提交信息
  if (props.action.relativeData &&
      Object.keys(props.action.relativeData).length) {
    params = {...params, ...props.action.relativeData}
  }
  crmLeadsSaveAPI(params).then(res => {
    createOption.loading = false

    ElMessage.success({message: props.action.type == 'update' ? '编辑成功' : '添加成功'})

    close()

    // 保存成功
    emits('save-success', {type: 'leads'})
  }).catch((e) => {
    console.log("e", e)
    createOption.loading = false
  })
}

/**
 * 验证唯一
 */
function UniquePromise({field, value}) {
  return hookCustomFields.getUniquePromise(field, value, props.action)
}

/**
 * change
 */
function formChange(field, index, value, valueList) {
  console.log("formChange", field, index, value, valueList)
  if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
      field.remark === 'options_type' &&
      field.optionsData) {
    const {
      fieldForm,
      fieldRules
    } = hookCustomFields.getFormContentByOptionsChange(createOption.fieldList, createOption.fieldForm)
    createOption.fieldForm = fieldForm
    createOption.fieldRules = fieldRules
  } else {
    fieldForm.value[field.field] = value
    console.log(fieldForm)
  }
}

/**
 * 地址change
 */
function otherChange(data, field) {
  // .$set(.fieldForm, field.field, data.value)
  createOption.fieldForm[field.field] = data.value
  // .$refs.crmForm.validateField(field.field)
  crmFormRef.value.validateField(field.field)
}


/**
 * 关闭
 */
function close() {
  emits('close')
}

</script>


<style lang="scss" scoped>
</style>
